<template>
  <el-dialog model-value:visible="visible" :close-on-click-modal="false" append-to-body
             title="选择位置" width="500px" @close="close">
    <flexbox align="stretch">
      <flexbox-item>
        <div class="area-title">定位</div>
        <el-autocomplete v-model="searchInput"
                         :fetch-suggestions="querySearchAsync"
                         style="width: 100%;"
                         placeholder="请输入详细位置名称"
                         @blur="inputBlur"
                         @focus="inputFocus"
                         @select="handleSelect">
          <template v-slot=" { item1 }">
            <div class="name">
              {{ item1.address + item1.title }}
            </div>
          </template>
        </el-autocomplete>
        <div ref="myMap" class="map"/>
      </flexbox-item>
    </flexbox>
    <template v-slot:footer>
      <span class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="selectSure">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>

import VDistpicker from '/src/szcomponent/VDistpicker'
import {getBaiduMap} from '/src/utils'
import {isEmpty} from '/src/utils/types'
import {nextTick, ref, watch} from "vue";

defineOptions({
  name: 'WkLocationPointDialog',
})

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  value: {
    type: Object,
    default: () => {
      return {}
    }
  }
})


const emits = defineEmits(['update:visible', 'select'])


const map = ref(null)
const searchInput = ref('') // 搜索
const searchCopyInput = ref('') // 避免修改
const pointAddress = ref(null) // 经纬度点

const myMap = ref();

watch(() => props.visible, (val) => {
  if (val) {
    nextTick(() => {
      getBaiduMap().then(() => {
        const map = new BMap.Map(myMap.value, {enableMapClick: true})
        let point = new BMap.Point(116.404, 39.915)
        if (props.value) {
          if (!isEmpty(props.value.lat) && !isEmpty(props.value.lng)) {
            point = new BMap.Point(props.value.lng, props.value.lat)
          }

          if (!isEmpty(props.value.address)) {
            props.searchInput = props.value.address
            props.searchCopyInput = props.searchInput
          }
        }

        if (!props.value ||
            (props.value && isEmpty(props.value.lat) && isEmpty(props.value.lng)
                && isEmpty(props.value.address))
        ) {
          // 定位逻辑
          let geolocation = new BMap.Geolocation()
          geolocation.getCurrentPosition(function (r) {
            if (getStatus() == BMAP_STATUS_SUCCESS) {
              var myGeo = new BMap.Geocoder({extensions_town: true})
              // 根据坐标得到地址描述
              myGeo.getLocation(r.point, function (result) {
                if (result) {
                  searchInput.value = result.address
                  searchCopyInput.value = result.address
                  addMarkerLabel(result.point)
                  result.title = ''
                  pointAddress.value = result
                }
              })
            }
          })
        }
        map.centerAndZoom(point, 14)
        map.enableScrollWheelZoom()
        map.value = map
        addMarkerLabel(point)
      })
    })
  }
})


function querySearchAsync(queryString, cb) {
  if (queryString) {
    let options = {
      onSearchComplete: function (results) {
        if (local.getStatus() == BMAP_STATUS_SUCCESS) {
          let address = []
          for (let i = 0; i < results.getCurrentNumPois(); i++) {
            address.push(results.getPoi(i))
          }
          cb(address)
        } else {
          cb([])
        }
      },
      pageCapacity: 20
    }
    let local = new BMap.LocalSearch(map.value, options)
    local.search(queryString)
  } else {
    cb([])
  }
}

/**
 * 搜索结果选择
 **/
function handleSelect(item) {
  searchInput.value = item.address + item.title
  searchCopyInput.value = searchInput.value // 只能通过这种方式修改

  addMarkerLabel(item.point)
  pointAddress.value = item
}

/**
 * Input 失去焦点  searchInput 只能通过选择更改
 **/
function inputBlur() {
  if (searchCopyInput.value !== searchInput.value) {
    searchInput.value = searchCopyInput.value
  }
}

function inputFocus() {
  searchCopyInput.value = searchInput.value
}

/**
 * 创建标注
 */
function addMarkerLabel(point) {
  map.value.clearOverlays()
  map.value.centerAndZoom(point, 14)
  map.value.addOverlay(new BMap.Marker(point))
}


/**
 * 关闭
 */
function close() {
  emits('update:visible', false)
}

/**
 * 确定选择
 */
function selectSure() {
  emits('select', pointAddress.value)
  close()
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.map {
  height: 150px;
  width: 100%;
  overflow: hidden;
  margin-top: 5px;
}

.area-title {
  font-size: 12px;
  color: #aaa;
  padding-bottom: 10px;
}

.distpicker-address-wrapper :deep(select) {
  height: 34px;
  font-size: 12px;
  border-radius: 0.1rem;
}

:deep(.el-dialog__body) {
  padding: 10px 20px 20px;
}
</style>
